

import java.io.DataInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.util.List;

import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration;

/**
 * Servlet implementation class DownloadServlet
 */
public class DownloadServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;
       
    /**
     * @see HttpServlet#HttpServlet()
     */
    public DownloadServlet() {
        super();
        // TODO Auto-generated constructor stub
    }

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
		System.out.println("download servlet");
		String file_id=request.getParameter("file_id");
		String original_filename="";
		
		
		
		
		SessionFactory sessionFactory = new Configuration().configure().buildSessionFactory();
		Session session = sessionFactory.openSession();
		Query query1 = session.createQuery("select g.fileName from Lib g where g.fileID = "+file_id);

		List<String> list=query1.list();
		String type=list.get(0).substring(list.get(0).indexOf('.'));
		
		System.out.println(file_id);
		System.out.println(type);
		File f= new File("c:\\temp\\"+file_id+type);
		int length   = 0;
		ServletOutputStream op  = response.getOutputStream();
		ServletContext context  = getServletConfig().getServletContext();
		String mimetype = context.getMimeType( file_id );


		response.setContentType( (mimetype != null) ? mimetype : "application/octet-stream" );
		response.setContentLength( (int)f.length() );
		response.setHeader( "Content-Disposition", "attachment; filename=\"" + original_filename + "\"" );

		//
		//  Stream to the requester.
		//
		byte[] bbuf = new byte[1024];
		DataInputStream in = new DataInputStream(new FileInputStream(f));

		System.out.println("---");
		while ((in != null) && ((length = in.read(bbuf)) != -1))
		{
			op.write(bbuf,0,length);
		}
		System.out.println("!@!");
		in.close();
		op.flush();
		op.close();

	
	}

}
